﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;

#region 引用SS命名空间
using SuperSocket.SocketEngine;
using SuperSocket.SocketBase;
using SS.Server.AppServer;
using Mode;
using Newtonsoft.Json;
using SS.Server.AppSession;
#endregion
namespace SS.Server
{
    class Program
    {
        public static ChatServer appServer;

        private static int Count = 0;
        private static int ConnectedCount = 0;
        private static int StopCount = 0;
        private static int ErrorCount = 0;
        private static int ClientCount = 1000;

        static void Main(string[] args)
        {
            appServer = new ChatServer();
            if (appServer.Setup(5000)==false)
            {
                Console.WriteLine("IpAndEnpoint Set Failed");
                return;
            }
            appServer.NewSessionConnected += appServer_NewSessionConnected;
            appServer.NewRequestReceived += AppServer_NewRequestReceived;
            appServer.SessionClosed += AppServer_SessionClosed;

            if (appServer.Start()==false)
            {
                Console.WriteLine("Server Start Failed");
                return;
            }

            Console.WriteLine("Hello");
            Console.ReadKey();


        }

        private static void AppServer_SessionClosed(AppSession.DemoSession session, CloseReason value)
        {
            Console.WriteLine("Client Is Closed:" + session.SessionID);
            Console.WriteLine("当前客户端个数：" + appServer.SessionCount);
        }

        private static void AppServer_NewRequestReceived(AppSession.DemoSession session, SuperSocket.SocketBase.Protocol.BinaryRequestInfo requestInfo)
        {
            //这里完成后，要把协议体的数据丢给线程去处理

            #region 1、测试接收客户端发送过来的DataSet成功
            
            Console.WriteLine(requestInfo.Body.Length);
            DataSet ds = SerializationHelpers.ByteToObject(requestInfo.Body, 0, requestInfo.Body.Length) as DataSet;
            string DsStr = ConvertJson.ToJson(ds);
            Console.WriteLine(DsStr);

            ////将接收到的DataSet原封不动发回给客户端
            byte[] info = SerializationHelpers.ObjectToByte(ds);
            var o = new ArraySegment<byte>(BitConverter.GetBytes(info.Length).Concat(info).ToArray());
            session.Send(o);
            Console.WriteLine(info.Length);
            
            #endregion

            #region 2、测试接收客户端发送过来的Mode.Message实例对象
            /*
            Console.WriteLine(requestInfo.Body.Length);
            MessageStr ms = SerializationHelpers.ByteToObject(requestInfo.Body,0,requestInfo.Body.Length) as MessageStr;
            Console.WriteLine("接收到的数据长度：{0}",requestInfo.Body.Length);
            Console.WriteLine("Msg:{0}",ms.Msg);
            Console.WriteLine("Name:{0}", ms.Name);

            //显示当前有多少个客户端在线
            Console.WriteLine("当前客户端个数：" + appServer.SessionCount);
            */
            #endregion

            #region 3、测试传输Byte+infoType类型实例
            /*
            MessageByte MsByte = SerializationHelpers.ByteToObject(requestInfo.Body,0,requestInfo.Body.Length) as MessageByte;
            Console.WriteLine(MsByte.infoType.ToString());
            if (MsByte.infoType==InformationTypes.AddEmployee)
            {
                Console.WriteLine("AddEmployee");
                MessageStr mss = new MessageStr { Name="徐贤智",Msg="两兄弟整天打架"};
                byte[] info = SerializationHelpers.ObjectToByte(mss);

                MessageByte SendMsgByte = new MessageByte { infoType = InformationTypes.AddEmployee, MsgByte = info };
                byte[] Sendinfo = SerializationHelpers.ObjectToByte(SendMsgByte);
                var o = new ArraySegment<byte>(BitConverter.GetBytes(Sendinfo.Length).Concat(Sendinfo).ToArray());
                session.Send(o);
            }
            if (MsByte.infoType == InformationTypes.DeleteEmployee)
            {
                Console.WriteLine("DeleteEmployee");
            }
            */

            /*

            byte[] bytes = BitConverter.GetBytes(Convert.ToInt16(e.Package.Key)).Concat(e.Package.Data).ToArray();
            MessageByte msb = SerializationHelpers.ByteToObject(bytes, 0, bytes.Length) as MessageByte;
            MessageStr ms;
            if (msb.infoType == InformationTypes.AddEmployee)
            {
                ms = SerializationHelpers.ByteToObject(msb.MsgByte, 0, msb.MsgByte.Length) as MessageStr;
                Console.WriteLine(ms.Msg);
                Console.WriteLine(ms.Name);
            }
*/

            //     Console.WriteLine(info.Length);
            #endregion

            #region 4、测试使用多线程
            /*
            MessageByte MsByte = SerializationHelpers.ByteToObject(requestInfo.Body, 0, requestInfo.Body.Length) as MessageByte;
  //          Console.WriteLine(MsByte.infoType.ToString());
            try
            {
                //实例化ThreadWithState类，为线程提供参数
                ThreadWithParam tws = new ThreadWithParam(session, requestInfo);
                // 创建执行任务的线程，并执行
                Thread t = new Thread(new ThreadStart(tws.ThreadProc));
                t.Start();
                t.Join();

            }
            catch (Exception errException)
            {
                Console.WriteLine(errException.ToString());
            }
            */
            #endregion
        }

        private static void appServer_NewSessionConnected(AppSession.DemoSession session)
        {//有客户端连接上来时处理的事件，比如回发欢迎信息

            #region 1、读取数据库并发送回客户端 成功
            /*
            Console.WriteLine("当前客户端个数：" + appServer.SessionCount);

            string tmpStr = "Data Source=" + "SINOMAC" + "\\SQLEXPRESS;Initial Catalog=PrintPMIS;User Id=sa;Password=ssa;";
            Console.WriteLine("client is connected");

            #region 测试读取数据库的DataSet

            DataSet ds = new DataSet();
            try
            {
                //读取数据库
                SqlConnection con = new SqlConnection(tmpStr);
                SqlDataAdapter dap = new SqlDataAdapter("PRO_Porject_AllView", con);
                dap.SelectCommand.CommandType = CommandType.StoredProcedure;

                dap.Fill(ds);
                con.Close();
            }
            catch// (Exception E)
            {

            }

            #endregion

            byte[] info = SerializationHelpers.ObjectToByte(ds);
            var o = new ArraySegment<byte>(BitConverter.GetBytes(info.Length).Concat(info).ToArray());
            session.Send(o);
            Console.WriteLine(info.Length);
            */
            #endregion


            #region 原来的代码   
            /*
            Interlocked.Increment(ref ConnectedCount);
            Message message = new Message() { Name = "test", Msg = "dsjidjisjdi" };
            byte[] bytes = BitConverter.GetBytes((short)1).Concat(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message))).ToArray();
            var o = new ArraySegment<byte>(BitConverter.GetBytes(bytes.Length).Concat(bytes).ToArray());
            session.Send(o);
            */
            #endregion
        }
    }
}
